package com.annet.token.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@ConditionalOnProperty(prefix = "annet.token",name = "security.type",havingValue = "config")
@Slf4j
@Component
public class AuthProperties {

    private static final String ORG_CODE = "orgCode";
    private static final String NAME = "name";
    private static final String UNAME = "uname";
    private static final String PWD_MD5 = "pwdMd5";
    private static final String SECRET_KEY = "secretKey";
    private static final String ENABLE_IPS = "enableIps";
    private static final String UNABLE_IPS = "unableIps";

    /**
     * 保存加载配置参数
     */
    private static Map<String, String> propertiesMap = new HashMap<>();

    /**
     * 加载属性
     */
    @PostConstruct
    public void loadProperties() throws Exception {
        // 获得PathMatchingResourcePatternResolver对象
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            // 加载resource文件(也可以加载resources)
//            Resource resource = resolver.getResource("classpath:config/token-security.properties");
            ClassPathResource resource = new ClassPathResource("config/token-security.properties");
            PropertiesFactoryBean config = new PropertiesFactoryBean();
            config.setLocation(resource);
            config.afterPropertiesSet();
            Properties prop = config.getObject();
            // 循环遍历所有得键值对并且存入集合
            for (String key : prop.stringPropertyNames()) {
                propertiesMap.put(key, (String) prop.get(key));
            }
        } catch (Exception e) {
//            throw new Exception("配置文件加载失败");
            log.error("配置文件加载失败");
        }
    }

    public String getOrgCode() {
        return propertiesMap.get(ORG_CODE);
    }

    public String getNAME() {
        return propertiesMap.get(NAME);
    }

    public String getUNAME() {
        return propertiesMap.get(UNAME);
    }

    public String getPwdMd5() {
        return propertiesMap.get(PWD_MD5);
    }
    public String getSecretKey() {
        return propertiesMap.get(SECRET_KEY);
    }

    public String getEnableIps() {
        return propertiesMap.get(ENABLE_IPS);
    }

    public String getUnableIps() {
        return propertiesMap.get(UNABLE_IPS);
    }
}
